﻿#include "hdataquery.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>

HDataQuery::HDataQuery(QObject *parent)
    : QObject (parent)
{

}

//把数据封装为json，通过QJsonDocument转成QByteArray传递
//QJsonObject代表一个json对象，即{xxx,xxx}中的内容。
//QJsonArray代表一个json数组，即[{obj},{obj},{obj}]。
QByteArray HDataQuery::getQua(const QString &name)
{
    QSqlQuery query(QString("select month,qua from data where plantName='%1'").arg(name));
    QJsonArray dataArray;

    int index = 0;
    while (query.next()) {
        QJsonObject object;
        object.insert("month", query.value(0).toJsonValue());
        object.insert("qua", query.value(1).toJsonValue());
        dataArray.insert(index++, object);
    }
    //qDebug()<<dataArray;

    QJsonDocument doc(dataArray);
    //qDebug()<<doc.toJson();
    return doc.toJson();
}

int HDataQuery::dbFields()
{
    QSqlQuery query(QString("select * from data limit 1"));
    int fields = 0;
    if (query.next())
        fields = query.record().count();
    return fields;
}

QStringList HDataQuery::dbFieldNames()
{
    QSqlQuery query(QString("select * from data limit 1"));
    QSqlRecord record;
    if (query.next()) {
        record = query.record();
    }
    QStringList names;
    for (int i = 0; i < record.count(); ++i) {
        names << record.fieldName(i);
    }
    return names;
}

QByteArray HDataQuery::getScore(const QString &name)
{
    QSqlQuery query(QString("select month,score from data where plantName='%1' ORDER BY month DESC; ").arg(name));
    QJsonArray dataArray;
    int index = 0;
    while (query.next()) {
        QJsonObject object;
        object.insert("month", query.value(0).toJsonValue());
        object.insert("score", query.value(1).toJsonValue());
        dataArray.insert(index++, object);
    }

    QJsonDocument doc(dataArray);
    return doc.toJson();
}

QByteArray HDataQuery::getPlants()
{
    QSqlQuery query(QString("select DISTINCT plantName from data"));
    QJsonArray dataArray;
    int index = 0;
    while (query.next()) {
        dataArray.insert(index++, query.value(0).toJsonValue());
    }

    QJsonDocument doc(dataArray);
    return doc.toJson();
}

int HDataQuery::getPlantCountByInverter(const QString &name)
{
    QSqlQuery query(QString("select DISTINCT plantName from data where inverterName='%1'").arg(name));
    int count = 0;
    while (query.next()) {
        ++count;
    }
    return count;
}

float HDataQuery::getScoreByInverter(const QString &name)
{
    QSqlQuery query(QString("select sum(score) from data where inverterName='%1'").arg(name));
    if (query.next())
        return query.value(0).toFloat();
    else
        return 0.0;
}
